package com.muh.exchange;

import com.muh.util.RabbitMQUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class FanoutConsumer {
    private static final String EXCHANGE_NAME = "fanoutExchange";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitMQUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);//必须要是 fanout 类型
        String queueName = channel.queueDeclare().getQueue();//临时对列
        System.out.println(queueName);
        channel.queueBind(queueName, EXCHANGE_NAME, "");//交换机绑定对列
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("---------------------------");
                System.out.println("routingKey: " + envelope.getRoutingKey());
                System.out.println("contentType: " + properties.getContentType());
                long deliveryTag = envelope.getDeliveryTag();
                System.out.println("deliveryTag: " + deliveryTag);
                System.out.println("content: " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, false);
                System.out.println("---------------------------");
            }
        };
        channel.basicConsume(queueName, consumer);//自动应答临时对列的名称
    }
}
